<template>
  <input type="file" @change="onChange" />
</template>

<script lang="ts" setup name="Video">
const onChange = async (e: Event) => {
  const file = (e.target as HTMLInputElement).files as FileList
  await fileToVideo(file[0], 0)
  await fileToVideo(file[0], 3)
  await fileToVideo(file[0], 6)
  await fileToVideo(file[0], 9)
}

const fileToVideo = (file: File, currentTime = 0) => {
  if (!file) return
  return new Promise((resolve) => {
    const url = window.URL.createObjectURL(file)
    const videoEl = document.createElement('video')
    videoEl.src = url
    videoEl.width = 160
    videoEl.height = 90
    videoEl.muted = true
    videoEl.currentTime = currentTime
    videoEl.autoplay = true

    videoEl.oncanplay = function () {
      const canvasEl = document.createElement('canvas')
      canvasEl.width = 160
      canvasEl.height = 90
      const ctx = canvasEl.getContext('2d')
      ctx?.drawImage(videoEl, 0, 0, videoEl.width, videoEl.height)
      canvasEl.toBlob((blob) => {
        const previewURL = window.URL.createObjectURL(
          new File([blob as Blob], `${currentTime}-image`)
        )
        const appEl = document.querySelector('#app') as Element
        const imgEl = document.createElement('img')

        imgEl.src = previewURL
        appEl.appendChild(imgEl)
        resolve({
          previewURL,
        })
      })
    }
  })
}
</script>

<style lang="scss" scoped></style>
